<template>
  <div class="owner-management">
    <!-- 页面标题 -->
    <div class="page-title">
      <h2>业主管理</h2>
    </div>

    <!-- 页面说明 -->
    <div class="page-desc">
      无关联房屋住户进入待审核列表；住户迁入房屋后进入已迁入列表；审核不通过进入未通过列表；管理员将住户迁出房屋后，住户进入已迁出列表。
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="已迁入" name="movedIn"></el-tab-pane>
      <el-tab-pane label="已迁出" name="movedOut"></el-tab-pane>
    </el-tabs>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">添加</el-button>
      <el-button type="success" @click="handleImport">导入</el-button>
      <el-button v-if="activeTab === 'movedIn'" @click="handleBatchMoveOut">迁出</el-button>
    </div>

    <!-- 搜索与筛选 -->
    <div class="search-filter">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入姓名/房号/手机号搜索"
        style="width: 200px; margin-right: 10px;"
        @keyup.enter="handleSearch"
      ></el-input>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="primary" icon="el-icon-filter" @click="handleFilter">筛选</el-button>
    </div>

    <!-- 业主表格 -->
    <el-table 
      :data="ownerList" 
      border 
      style="width: 100%; margin-top: 20px;"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="姓名" prop="homeownerName" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.homeownerName }}</span>
          <i class="el-icon-plus" style="margin-left: 5px; color: #409EFF; cursor: pointer;" @click="handleAddFamily(scope.row)"></i>
        </template>
      </el-table-column>
      <el-table-column label="手机号" prop="homeownerPhone" width="140"></el-table-column>
      <el-table-column label="小区" prop="community.communityName" width="120"></el-table-column>
      <el-table-column label="楼宇" prop="building.buildingName" width="120"></el-table-column>
      <el-table-column label="单元" prop="room.unitId" width="100"></el-table-column>
      <el-table-column label="房号" prop="room.roomNumber" width="130"></el-table-column>
      <el-table-column label="住户身份" prop="status" width="120">
        <template slot-scope="scope">
          <span>{{ getStatusText(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <!-- 已迁入页面不显示有效期和登录次数字段 -->
      <el-table-column v-if="activeTab === 'movedOut'" label="有效期" prop="validityPeriod" width="100">
        <template slot-scope="scope">
          <span>{{ getValidityText(scope.row.validityPeriod) }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="activeTab === 'movedOut'" label="登录次数" prop="loginCount" width="100"></el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleDetail(scope.row)">详情</el-button>
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <!-- 根据当前页面状态动态渲染迁入/迁出按钮 -->
          <el-button 
            v-if="activeTab === 'movedOut'" 
            type="text" 
            size="small" 
            @click="handleMoveIn(scope.row)"
          >
            迁入
          </el-button>
          <el-button 
            v-if="activeTab === 'movedIn'" 
            type="text" 
            size="small" 
            @click="handleMoveOut(scope.row)"
          >
            迁出
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; text-align: right;"
    >
    </el-pagination>

    <!-- 详情弹窗 -->
    <el-dialog
      title="业主详情"
      :visible.sync="detailDialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentHomeowner" class="detail-content">
        <!-- 基本信息 -->
        <el-card class="info-card" shadow="never">
          <div slot="header" class="card-header">
            <span>基本信息</span>
          </div>
          <div class="info-grid">
            <div class="info-item">
              <label>姓名：</label>
              <span>{{ currentHomeowner.homeownerName }}</span>
            </div>
            <div class="info-item">
              <label>性别：</label>
              <span>{{ getSexText(currentHomeowner.homeownerSex) }}</span>
            </div>
            <div class="info-item">
              <label>手机号：</label>
              <span>{{ currentHomeowner.homeownerPhone }}</span>
            </div>
            <div class="info-item">
              <label>身份证号：</label>
              <span>{{ currentHomeowner.homeownerIdcard || '未填写' }}</span>
            </div>
            <div class="info-item">
              <label>微信号：</label>
              <span>{{ currentHomeowner.homeownerWechat || '未填写' }}</span>
            </div>
            <div class="info-item">
              <label>入住时间：</label>
              <span>{{ currentHomeowner.homeownerTime || '未填写' }}</span>
            </div>
          </div>
        </el-card>

        <!-- 房屋信息 -->
        <el-card class="info-card" shadow="never">
          <div slot="header" class="card-header">
            <span>房屋信息</span>
          </div>
          <div class="info-grid">
            <div class="info-item">
              <label>小区：</label>
              <span>{{ (currentHomeowner.community && currentHomeowner.community.communityName) || '未分配' }}</span>
            </div>
            <div class="info-item">
              <label>楼宇：</label>
              <span>{{ (currentHomeowner.building && currentHomeowner.building.buildingName) || '未分配' }}</span>
            </div>
            <div class="info-item">
              <label>单元：</label>
              <span>{{ (currentHomeowner.room && currentHomeowner.room.unitId) || '未分配' }}</span>
            </div>
            <div class="info-item">
              <label>房号：</label>
              <span>{{ (currentHomeowner.room && currentHomeowner.room.roomNumber) || '未分配' }}</span>
            </div>
            <div class="info-item">
              <label>住户身份：</label>
              <span>{{ getStatusText(currentHomeowner.status) }}</span>
            </div>
            <div class="info-item">
              <label>居住状态：</label>
              <span>{{ getLiveStatusText(currentHomeowner.liveStatus) }}</span>
            </div>
          </div>
        </el-card>

        <!-- 其他信息 -->
        <el-card class="info-card" shadow="never">
          <div slot="header" class="card-header">
            <span>其他信息</span>
          </div>
          <div class="info-grid">
            <div class="info-item">
              <label>户籍地址：</label>
              <span>{{ currentHomeowner.homeownerAddress || '未填写' }}</span>
            </div>
            <div class="info-item">
              <label>押金：</label>
              <span>{{ currentHomeowner.homeownerDeposit ? '¥' + currentHomeowner.homeownerDeposit : '未设置' }}</span>
            </div>
            <div class="info-item">
              <label>有效期：</label>
              <span>{{ getValidityText(currentHomeowner.validityPeriod) }}</span>
            </div>
            <div class="info-item full-width">
              <label>备注：</label>
              <span>{{ currentHomeowner.homeownerDesc || '无' }}</span>
            </div>
          </div>
        </el-card>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleEditFromDetail">编辑</el-button>
      </div>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      title="编辑业主"
      :visible.sync="editDialogVisible"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="editRules"
        label-width="120px"
        v-loading="editLoading"
      >
        <div class="form-section">
          <h3>基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="homeownerName">
                <el-input v-model="editForm.homeownerName" placeholder="请输入姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="homeownerSex">
                <el-select v-model="editForm.homeownerSex" placeholder="请选择性别" style="width: 100%">
                  <el-option label="男" :value="1"></el-option>
                  <el-option label="女" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="手机号" prop="homeownerPhone">
                <el-input v-model="editForm.homeownerPhone" placeholder="请输入手机号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="homeownerIdcard">
                <el-input v-model="editForm.homeownerIdcard" placeholder="请输入身份证号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="微信号" prop="homeownerWechat">
                <el-input v-model="editForm.homeownerWechat" placeholder="请输入微信号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入住时间" prop="homeownerTime">
                <el-date-picker
                  v-model="editForm.homeownerTime"
                  type="date"
                  placeholder="请选择入住时间"
                  style="width: 100%"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="homeownerDesc">
                <el-input
                  v-model="editForm.homeownerDesc"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注信息"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit" :loading="editSaving">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { homeownerApi } from '@/api/homeowner'

import request from '@/utils/request'

export default {
  data() {
    return {
      activeTab: "movedIn", // 默认激活"已迁入"标签页
      ownerList: [],
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 总条数
      loading: false, // 加载状态
      searchKeyword: '', // 搜索关键词
      selectedRows: [], // 选中的行
      
      // 详情弹窗相关
      detailDialogVisible: false,
      currentHomeowner: null,
      
      // 编辑弹窗相关
      editDialogVisible: false,
      editLoading: false,
      editSaving: false,
      editForm: {
        homeownerId: '',
        homeownerName: '',
        homeownerPhone: '',
        homeownerSex: null,
        homeownerCard: '',
        homeownerTime: '',
        homeownerWechat: '',
        homeownerIdcard: '',
        homeownerDesc: ''
      },
      editRules: {
        homeownerName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        homeownerPhone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        homeownerSex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        homeownerIdcard: [
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.loadData();
  },
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true;
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          liveStatus: this.getLiveStatusByTab(this.activeTab),
          title: this.searchKeyword || null,
          status: 1 // 设置默认状态为1，表示正常状态的业主
        };
        
        console.log('请求参数:', params); // 添加调试日志
        
        const response = await homeownerApi.getHomeownerPage(params);
        console.log('响应数据:', response); // 添加调试日志
        
        if (response.code === 200) {
          this.ownerList = response.data.records || [];
          this.total = response.data.total || 0;
          console.log('业主列表数据:', this.ownerList); // 添加调试日志
          console.log('总数据量:', this.total); // 添加调试日志
        } else {
          console.error('接口返回错误:', response);
          this.$message.error(response.message || '获取数据失败');
        }
      } catch (error) {
        console.error('获取业主数据失败:', error);
        this.$message.error('获取数据失败');
      } finally {
        this.loading = false;
      }
    },

    // 根据标签页获取liveStatus
    getLiveStatusByTab(tab) {
      const statusMap = {
        'movedIn': 0, // 已迁入 - liveStatus = 0
        'movedOut': 1  // 已迁出 - liveStatus = 1
      };
      return statusMap[tab] || 0;
    },

    // 标签页切换
    handleTabClick(tab) {
      this.activeTab = tab.name;
      this.currentPage = 1;
      this.loadData();
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.loadData();
    },

    // 筛选
    handleFilter() {
      // TODO: 实现筛选功能
      this.$message.info('筛选功能待实现');
    },

    // 添加业主
    handleAdd() {
      this.$router.push('/data-center/add-homeowner');
    },

    // 导入
    handleImport() {
      // TODO: 实现导入功能
      this.$message.info('导入功能待实现');
    },

    // 批量迁出
    async handleBatchMoveOut() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要迁出的业主');
        return;
      }
      this.$confirm(`确定要迁出选中的 ${this.selectedRows.length} 位业主吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const promises = this.selectedRows.map(row => 
            homeownerApi.moveOut(row.homeownerId)
          );
          const results = await Promise.all(promises);
          
          const successCount = results.filter(result => result.code === 200).length;
          const failCount = results.length - successCount;
          
          if (failCount === 0) {
            this.$message.success(`批量迁出成功，共处理 ${successCount} 位业主`);
          } else {
            this.$message.warning(`批量迁出完成，成功 ${successCount} 位，失败 ${failCount} 位`);
          }
          
          this.loadData();
        } catch (error) {
          console.error('批量迁出失败:', error);
          this.$message.error('批量迁出失败');
        }
      });
    },


    // 迁入
    async handleMoveIn(row) {
      this.$confirm('确定要迁入该业主吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await homeownerApi.moveIn(row.homeownerId);
          if (response.code === 200) {
            this.$message.success('迁入成功');
            this.loadData();
          } else {
            this.$message.error(response.message || '迁入失败');
          }
        } catch (error) {
          console.error('迁入失败:', error);
          this.$message.error('迁入失败');
        }
      });
    },

    // 迁出
    async handleMoveOut(row) {
      this.$confirm('确定要迁出该业主吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await homeownerApi.moveOut(row.homeownerId);
          if (response.code === 200) {
            this.$message.success('迁出成功');
            this.loadData();
          } else {
            this.$message.error(response.message || '迁出失败');
          }
        } catch (error) {
          console.error('迁出失败:', error);
          this.$message.error('迁出失败');
        }
      });
    },

    // 添加家庭成员
    handleAddFamily(row) {
      // TODO: 实现添加家庭成员功能
      this.$message.info('添加家庭成员功能待实现');
    },

    // 初始化测试数据
    async handleInitTestData() {
      this.$confirm('确定要初始化测试数据吗？这将创建一些示例业主数据。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await homeownerApi.initTestData();
          if (response.code === 200) {
            this.$message.success(response.message || '初始化测试数据成功');
            this.loadData(); // 重新加载数据
          } else {
            this.$message.error(response.message || '初始化测试数据失败');
          }
        } catch (error) {
          console.error('初始化测试数据失败:', error);
          this.$message.error('初始化测试数据失败');
        }
      });
    },

    // 表格选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '业主本人',
        2: '家庭成员',
        3: '租户'
      };
      return statusMap[status] || '未知';
    },

    // 获取有效期文本
    getValidityText(validityPeriod) {
      if (validityPeriod === 0) {
        return '长期';
      } else if (validityPeriod > 0) {
        return `${validityPeriod}天`;
      }
      return '未知';
    },

    // 获取性别文本
    getSexText(sex) {
      const sexMap = {
        1: '男',
        2: '女'
      };
      return sexMap[sex] || '未知';
    },

    // 获取居住状态文本
    getLiveStatusText(liveStatus) {
      const liveStatusMap = {
        0: '已迁入',
        1: '已迁出'
      };
      return liveStatusMap[liveStatus] || '未知';
    },

    // 查看详情
    async handleDetail(row) {
      try {
        const response = await homeownerApi.getHomeownerById(row.homeownerId);
        if (response.code === 200) {
          this.currentHomeowner = response.data;
          this.detailDialogVisible = true;
        } else {
          this.$message.error(response.message || '获取业主详情失败');
        }
      } catch (error) {
        console.error('获取业主详情失败:', error);
        this.$message.error('获取业主详情失败');
      }
    },

    // 编辑业主
    async handleEdit(row) {
      try {
        const response = await homeownerApi.getHomeownerById(row.homeownerId);
        if (response.code === 200) {
          this.currentHomeowner = response.data;
          this.initEditForm(response.data);
          this.editDialogVisible = true;
        } else {
          this.$message.error(response.message || '获取业主信息失败');
        }
      } catch (error) {
        console.error('获取业主信息失败:', error);
        this.$message.error('获取业主信息失败');
      }
    },

    // 从详情弹窗进入编辑
    handleEditFromDetail() {
      this.detailDialogVisible = false;
      this.initEditForm(this.currentHomeowner);
      this.editDialogVisible = true;
    },

    // 初始化编辑表单
    initEditForm(data) {
      this.editForm = {
        homeownerId: data.homeownerId,
        homeownerName: data.homeownerName,
        homeownerPhone: data.homeownerPhone,
        homeownerSex: data.homeownerSex,
        homeownerCard: data.homeownerCard || '',
        homeownerTime: data.homeownerTime || '',
        homeownerWechat: data.homeownerWechat || '',
        homeownerIdcard: data.homeownerIdcard || '',
        homeownerDesc: data.homeownerDesc || ''
      };
    },

    // 保存编辑
    async handleSaveEdit() {
      try {
        await this.$refs.editForm.validate();
        
        this.editSaving = true;
        
        const response = await homeownerApi.updateHomeowner(this.editForm);
        
        if (response.code === 200) {
          this.$message.success('编辑业主成功');
          this.editDialogVisible = false;
          this.loadData(); // 重新加载数据
        } else {
          this.$message.error(response.message || '编辑业主失败');
        }
      } catch (error) {
        if (error.message) {
          this.$message.error(error.message);
        } else {
          console.error('编辑业主失败:', error);
          this.$message.error('编辑业主失败');
        }
      } finally {
        this.editSaving = false;
      }
    },


    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.loadData();
    },

    // 当前页码改变时触发
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadData();
    },
  },
};
</script>

<style scoped>
.owner-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-title {
  margin-bottom: 20px;
}

.page-title h2 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.page-desc {
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.operation-buttons {
  margin: 20px 0;
  display: flex;
  align-items: center;
}

.operation-buttons .el-button {
  margin-right: 10px;
  height: 36px;
  padding: 0 20px;
}

.search-filter {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.search-filter .el-input {
  margin-right: 10px;
}

.search-filter .el-button {
  height: 36px;
  padding: 0 20px;
}

/* 表格样式优化 */
.el-table {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-table th {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

/* 分页样式优化 */
.el-pagination {
  margin-top: 20px;
  text-align: right;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 标签页样式优化 */
.el-tabs {
  background-color: #fff;
  padding: 0 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-tabs__header {
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
}

.el-tabs__nav-wrap {
  padding: 0;
}

.el-tabs__item {
  height: 50px;
  line-height: 50px;
  padding: 0 20px;
  font-size: 14px;
  font-weight: 500;
}

.el-tabs__item.is-active {
  color: #409EFF;
  font-weight: 600;
}

/* 操作按钮样式 */
.el-button--text {
  padding: 0;
  margin-right: 10px;
  color: #409EFF;
}

.el-button--text:hover {
  color: #66b1ff;
}

/* 加载状态样式 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
}

/* 弹窗样式 */
.detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.info-card {
  margin-bottom: 20px;
}

.info-card:last-child {
  margin-bottom: 0;
}

.card-header {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.info-item {
  display: flex;
  align-items: flex-start;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-item label {
  font-weight: 600;
  color: #606266;
  min-width: 100px;
  margin-right: 10px;
}

.info-item span {
  color: #303133;
  flex: 1;
  word-break: break-all;
}

/* 编辑表单样式 */
.form-section {
  margin-bottom: 30px;
}

.form-section h3 {
  margin: 0 0 20px 0;
  padding: 10px 0;
  border-bottom: 2px solid #409EFF;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.form-section:last-child {
  margin-bottom: 0;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .owner-management {
    padding: 10px;
  }
  
  .operation-buttons {
    flex-wrap: wrap;
  }
  
  .search-filter {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-filter .el-input {
    margin-right: 0;
    margin-bottom: 10px;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>